<template>
  <view class="home-container">
    <z-paging ref="paging" v-model="shopList" @query="queryList">
      <template #top>
        <view class="head-box">
          <view class="head-bg" :style="'height:'+(150+statusBarHeight)+'px;'"></view>
          <view class="head-content" :style="'top:'+statusBarHeight+'px;'">
            <view class="head-motif flex-center-between">
              <view class="city flex-aj-center">
                <text class="brand">河马智洗</text>
                <navigator url="/pagesWash/city_select/city_select" hover-class="none">
                  <view class="flex-a-center">
                    <text class="cityName">{{ CommonStore.cityInfo.cityName }}</text>
                    <view class="triangle"></view>
                  </view>
                </navigator>
              </view>
              <view class="messages flex-aj-center" @tap="goTo(0)">
                <image src="http://www.xvopen.com/xiaoV/img1/msg.png" mode=""></image>
                <!-- <view v-if="msgTip>0" class="tips">{{msgTip}}</view> -->
              </view>
            </view>
            <!-- search -->
            <search disabled @click="goTo(1)"></search>
            <!-- banner -->
            <swiper-x :isRadius="true" :bannerList="bannerList"></swiper-x>
          </view>
        </view>
      </template>

      <!-- 新闻资讯 -->
      <view class="content_w">
        <navigator url="/pagesShop/information_list" hover-class="none">
          <view class="news-box flex-a-center">
            <image src="http://www.xvopen.com/xiaoV/img1/news.png" mode=""></image>
            <view class="vertical-line"></view>
            <view class="news-in-text">
              <swiper circular :autoplay="true" :interval="3000" :duration="1000" vertical="y" style="height: 50rpx;">
                <swiper-item v-for="(item,index) in newList" :key="index">
                  <view class="swiper-item">{{item.title}}</view>
                </swiper-item>
              </swiper>
            </view>
          </view>
        </navigator>
        <view class="mid-box flex-aj-center">
          <navigator url="/pagesShop/laundryList">
            <view class="item flex-aj-center">
              <image src="http://www.xvopen.com/xiaoV/img1/index-mid1.png" mode=""></image>
              <view class="txt">
                <view>洗衣小常识</view>
                立即查看
              </view>
            </view>
          </navigator>
          <navigator url="/pagesShop/beginner_tutorial">
            <view class="item flex-aj-center">
              <image src="http://www.xvopen.com/xiaoV/img1/index-mid2.png" mode=""></image>
              <view class="txt">
                <view>新手教程</view>
                立即查看
              </view>
            </view>
          </navigator>
          <!--        url="/pagesShop/self_support_apply"-->
          <view @click="goCooperation('/pagesShop/self_support_apply',1)">
            <view class="item flex-aj-center">
              <image src="http://www.xvopen.com/xiaoV/img1/index-mid3.png" mode=""></image>
              <view class="txt">
                <view>我要合作</view>
                立即查看
              </view>
            </view>
          </view>
        </view>
        <!-- 广告 -->
        <view class="ad-box" @click="goCooperation('/pagesShop/platformCoupons')">
          <image src="http://www.xvopen.com/xiaoV/img/mine-bg1.png" mode=""></image>
        </view>
        <!-- 部分门店信息 -->
        <view class="division-box">
          <view class="title flex-aj-center">
            <view class="line"></view>
            <text>部分门店信息</text>
            <view class="line"></view>
          </view>
          <view class="hint">
            默认显示{{ km }}公里范围内的门店
          </view>
        </view>
        <view class="shop-box">
          <view class="shop-item"  v-for="(item,index) in shopList" :key="index">
            <navigator class="flex" @click="goCooperation('/pagesShop/shop_details?storeId='+item.id+'&favorited='+item.favorited)" hover-class="none">
              <image class="shopImg" :src="item.images" mode=""></image>
              <view class="refer">
                <view class="refer-item1 flex-center-between">
                  <text class="text-ellipsis ellip1">{{item.storeShortName}}</text>
                  <image v-if="item.favorited==1" @click.stop="handleCollect(item.storeId,index,false)" src="http://www.xvopen.com/xiaoV/img1/heart-full.png" mode=""></image>
                  <image @click.stop="handleCollect(item.storeId,index,true)" v-else src="http://www.xvopen.com/xiaoV/img1/heart.png" mode=""></image>
                </view>
                <view class="refer-item2 flex-center-between">
                  <text class="text-ellipsis text-ellipsis2 ellip2">店铺简介：{{item.description}}
                  </text>
                  <text>{{item.collectStore}}人收藏过</text>
                </view>
                <view class="refer-item3 flex-center-between">
                  <view>
                    <star :starRate="item.rating"></star>
                    <view class="distance flex-a-center">
                      <image class="add" src="http://www.xvopen.com/xiaoV/img1/add.png" mode=""></image>
                       {{  item.distance.toFixed(3)}}km

                    </view>
                  </view>
                  <view class="btn">
                    <main-button :fontSize="'24rpx'" :height="'48rpx'" :width="'144rpx'" @click="goShopCooperation(item.id, item.storeId,item.favorited)">一键下单</main-button>
                  </view>
                </view>
              </view>
            </navigator>
          </view>
        </view>
        <view class="more_go" @click="goCooperation('/pagesWash/search_result')" >—————去加载更多数据—————</view>
        <view style="height: 300rpx;"></view>
      </view>

    </z-paging>
    <up-modal
      :show="showMSg"
      :content='content'
      :closeOnClickOverlay="true"
      :showCancelButton="true"
      @cancel="close"
      @close="close"
      @confirm="confirm"
    ></up-modal>
  </view>
</template>

<script setup>
import { systemStore } from '@/stores/system'
import { commonStore } from '@/stores/common'
import { useCustomStores } from '@/utils/hook'
import { newsList, storeDetailsId } from '@/api/pagesShop/index'
import { customerCancelShop } from '@/api/pagesMy/user'
import { onMounted, onUnmounted, ref, getCurrentInstance, watch } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { navigateTo, switchTab } from '@/utils/navigator'
import { advertisementList, qryIndexList, customerCollectionShop, recommendedRange } from '@/api/home'
const SystemStore = systemStore()
const CommonStore = commonStore()
const { proxy } = getCurrentInstance()
const app = getApp()
const statusBarHeight = ref('')
statusBarHeight.value = SystemStore.statusBarInfo.statusBarHeight + 10
const showMSg = ref(false)
const content = ref('当前未实名认证,请前往实名认证,完成实名认证后,加盟店铺')
const { userStore: { userInfo }, ShopStore } = useCustomStores()
const props = defineProps({
  cityName: {
    type: String
  },
  loading: {
    type: Boolean
  },
  loaded: {
    type: Boolean
  }
})
const km = ref(20)

// 消息条数
const msgTip = ref(5)
// 轮播图
const bannerList = ref([])
// 新闻
const	newList = ref([])
const countyIds = ref([])
// 店铺列表
const paging = ref(null)
const shopList = ref([])
// -----------------------------------function-------------
function goTo(index) {
  if (index == 0) {
    uni.navigateTo({
      url: '/pagesInfo/info'
    })
  } else if (index == 1) {
    uni.navigateTo({
      url: '/pagesWash/search'
    })
  }
}

watch(() => CommonStore.locationAuthorization, (newValue, oldValue) => {
  if (!newValue) {
    if (newValue === false) {
      wx.showModal({
        title: '提示',
        content: '当前未授权位置信息,是否去授权',
        success: function(res) {
          if (res.confirm) {
            wx.openSetting({
              success: (result) => {
                const { authSetting } = result
                if (authSetting['scope.userLocation']) {
                  loadLoaction()
                }
              },
              fail: error => {
                // reject(error)
              }
            })
          }
        }
      })
      console.log('ces')
    }
  } else {
    countyIds.value = [CommonStore.cityInfo.cityCode]
    paging.value.reload()
  }
}, { immediate: true, deep: true })

// 获取轮播图
// 收藏函数
const handleCollect = (id, index, flag) => {
  if (flag) {
    customerCollectionShop({ storeId: id }).then(res => {
      shopList.value[index].favorited = true
    })
  } else {
    customerCancelShop({
      storeIds: [id]
    }).then(res => {
      shopList.value[index].favorited = false
    })
  }
}

// 获取新闻资讯
function InformationList() {
  newsList({
    pageNum: 1,
    pageSize: 5
  }).then(res => {
    newList.value = res
  })
}
const queryList = (pageNo, pageSize) => {
  qryIndexList({
    pageNum: pageNo,
    pageSize: pageSize,
    latitude: CommonStore.cityInfo.latitude || null,
    longitude: CommonStore.cityInfo.longitude || null,
    countyIds: countyIds.value
  }).then(res => {
    paging.value.complete(res)
    /** ****需要存储第一项的店铺存起来用于首页的按键********/
    if (res.length > 0) {
      console.log('res', res)
      CommonStore.setShopStoreIndex((res[0]))
    }
  })
}
const loadAdvertisementList = async() => {
  let res = await advertisementList({
    pageNum: 1,
    pageSize: 100
  })

  res = res.filter(item => {
    return item.displayEnd == 'CLIENT'
  }
  )
  bannerList.value = res.map(item => {
    item.pic = item.adImageUrl
    return item
  })
  console.log('rows', rows)
}
const goCooperation = (url, flag) => {
  proxy.$checkLoginAndExecute(() => {
    if (flag) {
      if (!userInfo.idCard) {
        showMSg.value = true
        return
      }
      uni.navigateTo({
        url
      })
      return
    }
    uni.navigateTo({
      url
    })
    // 在这里执行你需要的操作
  })
}
const close = () => {
  showMSg.value = false
}
const confirm = () => {
  showMSg.value = false
  uni.navigateTo({
    url: `/pagesMy/real_name_auth`
  })
}
const goShopCooperation = (id, ids, favorited) => {
  storeDetailsId(id).then(res => {
    ShopStore.setShopInfo({
      ...res
    })
    uni.navigateTo({
      url: '/pages/cleaningOrder/index?storeId=' + ids + '&favorited=' + favorited
    })
  })
}
function loadLoaction() {
  var QQMapWX = require('../../static/qqmap-wx-jssdk.min.js')
  var qqmapsdk
  // 实例化API核心类
  qqmapsdk = new QQMapWX({
    key: 'LKJBZ-ILRL6-5GTSI-E443R-NEXIE-6QF2R'
  })
  uni.getLocation({
    type: 'gcj02',
    altitude: true,
    geocode: true,
    success: function(res) {
      // 逆地址解析
      qqmapsdk.reverseGeocoder({
        location: {
          latitude: res.latitude,
          longitude: res.longitude
        },
        success: function(result) {
          CommonStore.setCityInfo({
            latitude: res.latitude,
            longitude: res.longitude,
            cityCode: result.result.ad_info.city_code.replace('156', ''),
            cityName: result.result.ad_info.city
          })
          CommonStore.setLocationAuthorization(true)
        },
        fail: function(error) {
          console.log('error', error)
        }
      })
    },
    fail(err) {
      // 位置授权失败之后
      CommonStore.setLocationAuthorization(false)
      console.log(err, 'fail')
    }
  })
}

loadAdvertisementList()
// -----------------------------------onMounted-------------
onMounted(() => {
  // BannerList();
  InformationList()
  recommendedRange().then(res => {
    console.log('res', res)
    km.value = res
  })
  uni.$on('refreshList', () => {
    paging.value.reload()
  })
})

onUnmounted(() => {
  uni.$off('refreshList', () => {
    paging.value.reload()
  })
})
</script>

<style lang="scss">
.home-container{
  font-size: 24rpx;
}
.head-box{
  position: relative;
  height: 607rpx;
  .head-bg{
    width: 750rpx;
    // height: 286rpx;
    background-color: #6CABFD;
    background-image: linear-gradient(135deg, #6CABFD 0%, #57CAEC 50%, #4CEBDF 100%);
    border-radius: 0 0 50rpx 50rpx;
  }
  .head-content{
    position: absolute;
    left: 0;
  }
  .head-motif{
    width: 65%;
    margin: 0 24rpx;
    .city{
      min-width: 266rpx;
      text.brand{
        font-size: 36rpx;
        font-weight: bold;
        margin-right: 8rpx;
      }
      .cityName{
        font-size: 28rpx;
        margin-top: 7rpx;
      }
      .triangle{
        margin-top: 18rpx;
        margin-left: 12rpx;
      }
    }
  }

}
.content_w{
  position: relative;
  left: 0;
  top:-192rpx;
}
.news-box{
  margin: 205rpx 24rpx 24rpx;
  background-color: #fff;
  border-radius: 12rpx;
  box-shadow: 0 0 10rpx 1rpx rgba(200, 200, 200, 0.16);
  padding: 10rpx 24rpx;
  image{
    width: 48rpx;
    height: 48rpx;
  }
  .vertical-line{
    width: 2rpx;
    height: 24rpx;
    border-radius: 10rpx;
    background-color: #BFBFBF;
    margin: 0 20rpx;
  }
  .news-in-text{
    width: 477rpx;
    height: 32rpx;
    color: #222222;
  }
}
.mid-box{
  margin: 0 16rpx 24rpx;
  .item{
    width: 223rpx;
    height: 92rpx;
    margin: 8rpx;
    background-color: #fff;
    border-radius: 16rpx;
    box-shadow: 0 0 10rpx 1rpx rgba(220, 220, 220, 0.16);
    image{
      width: 55rpx;
      height: 55rpx;
      margin-right: 10rpx;
    }
    .txt{
      font-size: 18rpx;
      color: #4A698D;
      view{
        font-size: 26rpx;
        font-weight: bold;
        color: #334770;
        margin-bottom: 2rpx;
      }
    }

  }
}
.ad-box{
  margin: 0 24rpx;
  image{
    width: 704rpx;
    height: 159rpx;
    border-radius: 5rpx;
  }
}
.division-box{
  margin: 24rpx 0;
  .title{
    color: #222222;
    margin: 0 0 8rpx;
    .line{
      width: 181rpx;
      height: 1rpx;
      background-color: #D1D1D1;
    }
    text{
      margin: 0 24rpx;
    }
  }
  .hint{
    color: #BBBBBB;
    text-align: center;
  }

}
.more_go{
  margin-top: 20rpx;
  width: 100%;
  text-align: center;
  font-size: 28rpx;
  color: #bbb;
}

</style>
